
const base64 = require('base64.js');//Base64,hmac,sha1,crypto相关算法
require('hmac.js');
require('sha1.js');
const Crypto = require('crypto.js');

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */ 
const uploadFile = function (options, successc, failc) {
  var filePath=options.file.wxTempFilePath;
  if (!filePath || filePath.length < 9) {
    wx.showModal({
      title: '视频错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }

  var url="";
  let endpoint = options.uploadAddress.Endpoint;
  console.log("endpoint=",endpoint);
  console.log("endpoint.indexOf=",endpoint.search(/^https:\/\//));
  if(endpoint.search(/^https:\/\//)==0){
    let tempStr1=endpoint.substring(8,endpoint.length);
    console.log("tempStr1=",tempStr1);
    url="https://"+options.uploadAddress.Bucket+"."+tempStr1;
  }else if(endpoint.search(/^http:\/\//)==0){
    let tempStr1=endpoint.substring(7,endpoint.length);
    console.log("tempStr2=",tempStr1);
    url="http://"+options.uploadAddress.Bucket+"."+tempStr1;
  }else{
    wx.showModal({
      title: '获取到的上传地址错误',
      content: endpoint,
      showCancel: false,
    })
    return;
  }

  console.log('上传视频.....');

  const policyBase64 = getPolicyBase64(options.uploadAuth);
  const signature = getSignature(policyBase64,options.uploadAuth);//获取签名
  let formData={
      'key': options.uploadAddress.FileName,
      'policy': policyBase64,
      'OSSAccessKeyId': options.uploadAuth.AccessKeyId,
      'Signature': signature,
      'success_action_status': '200',
      "x-oss-security-token":options.uploadAuth.SecurityToken,
      // "ExpireUTCTime":env.ExpireUTCTime,
      // "Bucket":"outin-f683565a3e5711e9904700163e1a3b4a"
      // "uploads":null,

    }


  console.log("url=",url);
  console.log("options=",options);
  console.log("formData=",formData);

  //参数详见阿里云API文档
    //https://help.aliyun.com/document_detail/31988.html?spm=a2c4g.11186623.2.16.28ea3fa0mbNfSR
  wx.uploadFile({
    url: url,//开发者服务器 url
    filePath: options.file.wxTempFilePath,//要上传文件资源的路径
    name: 'file',//必须填file
    header:{
      "Content-Type":"video/mp4",

    },
    formData: formData,
    success: function (res) {
      if (res.statusCode != 200) {
        failc(new Error('上传错误:' + JSON.stringify(res)))
        return;
      }
      var videoUrl=url+"/"+options.uploadAddress.FileName;
      console.log("url.search=",url.search(/^.+\/$/))
        //   /\/$/ 或者 /^.+\/$/ 都可以
      if(url.search(/^.+\/$/)>-1){
        videoUrl=url+options.uploadAddress.FileName;
      }
       successc(videoUrl);
    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      failc(err);
    },
  })
}

const getPolicyBase64 = function (uploadAuth) {
  let date = new Date();
  date.setHours(date.getHours() + uploadAuth.Expiration);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": uploadAuth.ExpireUTCTime, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
      ["content-length-range", 0, 150 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64,uploadAuth) {
  const accesskey = uploadAuth.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
}

module.exports = uploadFile;